package com.yoofn.framework.widget

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.yoofn.framework.R

/**
 * Created by kalshen on 17-9-8.
 * @描述 多状态recyclerView布局
 */

class StatusRecyclerLayout : RelativeLayout {

    lateinit var recyclerView: RecyclerView
    lateinit var statusLayout: RelativeLayout

    /**
     * 集合为空时的布局
     */
    var emptyLayout: View? = null
    /**
     * 请求失败时的布局
     */
    var netFailedLayout: View? = null
    /**
     * 请求失败后的action
     */
    var netFailedAction: (() -> Unit)? = null

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        //获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusRecyclerLayout)
        val layout_empty_item = typedArray.getResourceId(R.styleable.StatusRecyclerLayout_layout_empty_item, R.layout.layout_item_empty)
        val layout_net_failed = typedArray.getResourceId(R.styleable.StatusRecyclerLayout_layout_net_failed, R.layout.layout_net_failed)

        typedArray.recycle()


        recyclerView = RecyclerView(context)
        statusLayout = RelativeLayout(context).apply {
            visibility = View.INVISIBLE

        }
        emptyLayout = LayoutInflater.from(context).inflate(layout_empty_item, statusLayout, false)
        netFailedLayout = LayoutInflater.from(context).inflate(layout_net_failed, statusLayout, false)
        netFailedLayout?.setOnClickListener { netFailedAction?.invoke()  }
        statusLayout.addView(emptyLayout)
        statusLayout.addView(netFailedLayout)
        addView(recyclerView, -1, -1)
        addView(statusLayout, -1, -1)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}


    /**
     * 集合为空时的回调
     */
    fun onItemsEmpty(isEmpty: Boolean) {
        statusLayout.visibility = if (isEmpty) View.VISIBLE else View.INVISIBLE
        emptyLayout?.let { it.visibility = if (isEmpty) View.VISIBLE else View.INVISIBLE }
        netFailedLayout?.let { it.visibility = View.INVISIBLE }
    }


    /**
     * 网络请求失败
     */
    fun onNetFailed() {
        statusLayout.visibility = View.VISIBLE
        emptyLayout?.let { it.visibility = View.INVISIBLE }
        netFailedLayout?.let { it.visibility = View.VISIBLE }
    }

}
